﻿using System;
using System.Collections.Generic;
using System.Windows.Input;
using EventAggregator;

namespace EAWpfSample
{
    public sealed class DoWorkCommand : ICommand
    {
        private bool _isExecutable;

        public DoWorkCommand()
        {
            IsExecutable = true;

            this.Subscribe(EventId.Default.WorkDone, HandleWorkDone);
        }

        private bool IsExecutable
        {
            get { return _isExecutable; }

            set
            {
                if (_isExecutable == value)
                {
                    return;
                }

                _isExecutable = value;

                RaiseCanExecuteChanged();
            }
        }

        #region ICommand Members

        public void Execute(object parameter)
        {
            IsExecutable = false;

            this.Send(EventId.Default.DoWork, new KeyValuePair<string, object>("TimeSpan", TimeSpan.FromSeconds(5)));
        }

        public bool CanExecute(object parameter)
        {
            return IsExecutable;
        }

        public event EventHandler CanExecuteChanged;

        #endregion

        private void RaiseCanExecuteChanged()
        {
            EventHandler handler = CanExecuteChanged;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        private void HandleWorkDone(EventMessage eventMessage)
        {
            this.Send(EventId.Default.Dispatch,
                      new KeyValuePair<string, object>(
                          "Dispatch",
                          new Action(() => IsExecutable = eventMessage.GetValue<bool>("WorkIsDone"))));
        }
    }
}